package cn.szsys.integration.helper.manager;

import cn.hutool.core.text.CharSequenceUtil;
import cn.szsys.integration.constants.AppConstant;
import cn.szsys.integration.ex.BusinessException;
import cn.szsys.integration.helper.business.IForwardHandlerChain;
import cn.szsys.integration.util.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Ryan
 * @since 2025-05-09
 **/
@Slf4j
public abstract class AbstractForwardHandlerChainManager<T> implements ApplicationContextAware {
    /**
     * 相关bean
     */
    protected Map<String, IForwardHandlerChain<T>> handlerChainMap = new HashMap<>(11);


    protected ApplicationContext applicationContext;

    /**
     * 选择bean并执行相关方法
     *
     * @param t        参数
     * @param beanName beanName
     * @return {@link R}
     * @author Ryan
     */
    public R handler(T t, String beanName) {
        IForwardHandlerChain<T> forwardHandlerChain = handlerChainMap.get(beanName);
        if (forwardHandlerChain == null) {
            throw new BusinessException("未配置bean");
        }
        log.info("选择bean并执行相关方法: {}, bean class:{}", beanName, forwardHandlerChain.getClass());
        return forwardHandlerChain.doHandle(t, Long.parseLong(getAccessRequestTime()));
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     * 获取接收到请求的开始时间
     *
     * @return {@link String}
     * @author Ryan
     */
    public String getAccessRequestTime() {
        //下游名称缩写
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String startTime = request.getHeader(AppConstant.START_TIME);
        return CharSequenceUtil.isBlank(startTime) ? System.currentTimeMillis() + "" : startTime;
    }
}
